package com.hbfec.fileserver.service;

import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.csource.fastdfs.ProtoCommon;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * TrackerServer线程池工厂类
 */
@Service
public class TrackerServerFactory implements PooledObjectFactory<TrackerServer> {
    private static final Logger LOGGER = LoggerFactory.getLogger(TrackerServerFactory.class);

    /**
     * makeObject
     *
     * @return 连接对象
     * @throws Exception Exception
     */
    public PooledObject<TrackerServer> makeObject() throws Exception {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        if (trackerServer == null || !ProtoCommon.activeTest(trackerServer.getSocket())) {
            throw new Exception(String.format("无法获取到TrackerServer连接：%s", trackerServer));
        }
        return new DefaultPooledObject<TrackerServer>(trackerServer);
    }

    /**
     * destroyObject
     *
     * @param pooledObject pooledObject
     * @throws Exception Exception
     */
    public void destroyObject(PooledObject<TrackerServer> pooledObject) throws Exception {
        try {
            TrackerServer trackerServer = pooledObject.getObject();
            if (trackerServer != null) {
                trackerServer.close();
            }
        } catch (Exception ex) {
            LOGGER.error("TrackerServer连接池回收资源时出现异常", ex);
        }
    }

    /**
     * validateObject
     *
     * @param pooledObject pooledObject
     * @return 验证结果
     */
    public boolean validateObject(PooledObject<TrackerServer> pooledObject) {
        TrackerServer trackerServer = pooledObject.getObject();
        try {
            if (trackerServer == null || !ProtoCommon.activeTest(trackerServer.getSocket())) {
                return false;
            }
        } catch (Exception ex) {
            LOGGER.error("TrackerServer连接池在验证资源可用性时出现异常", ex);
            return false;
        }
        return true;
    }

    /**
     * activateObject
     *
     * @param pooledObject pooledObject
     * @throws Exception Exception
     */
    public void activateObject(PooledObject<TrackerServer> pooledObject) throws Exception {

    }

    /**
     * passivateObject
     *
     * @param pooledObject pooledObject
     * @throws Exception Exception
     */
    public void passivateObject(PooledObject<TrackerServer> pooledObject) throws Exception {
    }
}
